package Gui;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import recomendation.Recomendation;
import track.playlistEntry;
import auth.User;

public class Playlist {
	private Display playlistDisplay;
	private Shell playlistShell;
	private static playlistEntry currSongE;
	private static playlistEntry nextSongE;
	private static Composite form;
	private static Browser browser;
	private static int currIndex = 0;
	public Playlist(Shell shellToClose, Shell shell, final User mUser, playlistEntry pE, final Main main){
		if(shellToClose!=null){
			shellToClose.dispose();
		}
		this.playlistDisplay = shell.getDisplay();
		this.playlistShell = new Shell (playlistDisplay);
		playlistShell.setBackgroundImage(new Image(playlistDisplay, "bgs/bg5.jpg"));
		main.addShell(playlistShell);
		main.setPlaylistActive();
		
		form = new Composite(shell,SWT.BORDER);  
		form.setVisible(false);
		browser = new Browser(form, SWT.NONE);	
		browser.setUrl("http://www.blanksite.com/");
		main.setBro(form);
		invokePlaylist(shell, playlistShell, playlistDisplay, pE, mUser, main);
	}
	public static void skipCell(Shell shell, String sBlank){
		Label mDummy = new Label(shell, SWT.NONE);
		mDummy.setLayoutData(new GridData(GridData.BEGINNING,GridData.CENTER,false,true));
		mDummy.setText(sBlank);
	}
	public static String putMinus(String s){
		String s2 = s;
		s2 = s2.replace(" ", "-");
		s2 = s2.toLowerCase();
		return s2;
	}
	public static String putMinusS(String s){
		String s2 = s;
		s2 = s2.replace(" ", "-");
		s2 = s2.toLowerCase();
		if(s2.length() > 10){
			s2 = s2.substring(0,10);
		}
		return s2;
	}
	public static String putLower(String s){
		String s2 = s;
		s2 = s2.replace(" ", "");
		s2 = s2.toLowerCase();
		return s2;
	}
	public static void invokePlaylist(Shell shell, final Shell playlistShell, final Display playlistDisplay, final playlistEntry pE, final User mUser, final Main main){
		Volume.adjustVolume(1, "");
		final Shell passShellForward = shell;
		playlistShell.setText("Playlist");
		playlistShell.setLocation(shell.getLocation().x + 50, shell.getLocation().y + 50);
		GridLayout gl = new GridLayout(1,false);
		playlistShell.setLayout(gl);
			
		Menu topMenu = new Menu(playlistShell,SWT.BAR);
		playlistShell.setMenuBar(topMenu);

		MenuItem SongFeatures = new MenuItem(topMenu,SWT.CASCADE);
		MenuItem closeBt = new MenuItem(topMenu,SWT.CASCADE);
		
		SongFeatures.setText("Song features");
		closeBt.setText("Close playlist");
		
		Menu songMenu = new Menu(playlistShell,SWT.DROP_DOWN);
		SongFeatures.setMenu(songMenu);
		
		MenuItem Play = new MenuItem(songMenu,SWT.PUSH);
		MenuItem Stop = new MenuItem(songMenu,SWT.PUSH);
		MenuItem Lyrics = new MenuItem(songMenu,SWT.PUSH);
		MenuItem Update = new MenuItem(songMenu,SWT.PUSH);
		final MenuItem incVol = new MenuItem(songMenu,SWT.PUSH);
		final MenuItem decVol = new MenuItem(songMenu,SWT.PUSH);
		final MenuItem Like = new MenuItem(songMenu,SWT.PUSH);
		final MenuItem Dislike = new MenuItem(songMenu,SWT.PUSH);
	
		Play.setText("Play\tCtrl+P");
		Stop.setText("Stop\tCtrl+S");
		Lyrics.setText("View lyrics\tCtrl+V");
		Update.setText("Update this song\tCtrl+U");
		incVol.setText("Increase volume\tCtrl+ +");
		decVol.setText("Decrease volume\tCtrl+ -");
		Like.setText("Like\tCtrl+L");
		Dislike.setText("Dislike\tCtrl+D");
		
		Play.setAccelerator(SWT.MOD1+'P');
		Stop.setAccelerator(SWT.MOD1+'S');
		Lyrics.setAccelerator(SWT.MOD1+'V');
		Update.setAccelerator(SWT.MOD1+'U');
		Like.setAccelerator(SWT.MOD1+'L');
		Dislike.setAccelerator(SWT.MOD1+'D');
		incVol.setAccelerator(SWT.MOD1+'+');
		decVol.setAccelerator(SWT.MOD1+'-');
	
		Label currSong = new Label(playlistShell, SWT.NONE);
		currSong.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,true));
		currSong.setText("                                          Current playing song is:                                          ");
		final Text currSongInfo = new Text(playlistShell,SWT.BORDER);
		currSongInfo.setLayoutData(new GridData(GridData.FILL,GridData.CENTER,true,false));
		currSongInfo.setEditable(false);
		
		skipCell(playlistShell, "");
		
		Label nextSong = new Label(playlistShell, SWT.NONE);
		nextSong.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,true));
		nextSong.setText("                                                  Next song will be:                                             ");
		
		final Text nextSongInfo = new Text(playlistShell,SWT.BORDER);
		nextSongInfo.setLayoutData(new GridData(GridData.FILL,GridData.CENTER,true,false));
		nextSongInfo.setEditable(false);
		
		skipCell(playlistShell, "");
		
		final Button addSongBt = new Button(playlistShell,0);
		addSongBt.setText("Add song to playlist");
		addSongBt.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,false));
		
		final Button randSongBt = new Button(playlistShell,0);
		randSongBt.setText("Random mode off");
		randSongBt.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,false));
		
		Button gotoSearchBt = new Button(playlistShell,0);
		gotoSearchBt.setText("Go to search");
		gotoSearchBt.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,false));
		
		Button nextSongBt = new Button(playlistShell,0);
		nextSongBt.setText("Next song");
		nextSongBt.setLayoutData(new GridData(GridData.CENTER,GridData.CENTER,false,false));
		
		int RowsToSkip = 5;
		for(int i=0;i<RowsToSkip;i++){
			skipCell(playlistShell, "");
		}
		
		final Button dummyBt = new Button(playlistShell,SWT.CHECK);
		dummyBt.setEnabled(false);
		dummyBt.setVisible(false);
		final Button firstBt = new Button(playlistShell,SWT.CHECK);
		firstBt.setSelection(false);
		firstBt.setVisible(false);
		
		playlistShell.setFocus();
		
		currSongE = pE;
		if(!mUser.getPlaylist().isEmpty()){
			nextSongE = mUser.getNonRandPe(currIndex);
			nextSongInfo.setText(nextSongE.sDescription());
		}else{
			nextSongInfo.setText("You have no songs in your playlist");
		}
		if(currSongE == null){
			addSongBt.setEnabled(false);
			currSongInfo.setText("No song to play");
		}else{
			browser.setUrl("http://www.blanksite.com/");
			addSongBt.setEnabled(true);
			currSongInfo.setText(currSongE.sDescription());
		}
		Play.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{		
							String sUrl = "http://www.outofscopes.com/getSong.php?artist="+putMinus(currSongE.getArtist().getName())+"&track="+putMinusS(currSongE.getSong().getName());
							if(checkUrl(sUrl)){
								browser.setUrl("http://www.blanksite.com/");
								MessageDialog.Error(playlistShell, "Error", "Audio for this song was not found");
							}else{
								browser.setUrl(sUrl);
							}
						}
					}
				}
		);
		
		Stop.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							browser.setUrl("http://www.blanksite.com/");
						}
					}
				}
		);
		
		Lyrics.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{						
							String tempLyrics = getLyrics(putMinus(currSongE.getSong().getName()), putMinus(currSongE.getArtist().getName()), playlistShell);
							if(tempLyrics!=null){
								lyricsS ls = new lyricsS(passShellForward, tempLyrics, main);
							}
						}
					}
				}
		);
		
		Update.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(mUser.isAdmin()){
							if(currSongE == null){
								MessageDialog.Error(playlistShell, "Error", "No song to play");
							}else{
								UpdateSong us = new UpdateSong(passShellForward, currSongE, main);
								addSongBt.setEnabled(true);
								currSongInfo.setText(currSongE.sDescription());
							}
						}else{
							MessageDialog.Error(playlistShell, "Error", "This option is for admins only");
						}
					}
				}
		);
		
		Like.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							Recomendation.doLike(currSongE, true);
						}
					}
				}
		);
		
		Dislike.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							Recomendation.doLike(currSongE, false);

						}
					}
				}
		);
		
		incVol.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							Volume.adjustVolume(0,"Inc");
						}
					}
				}
		);
		
		decVol.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							Volume.adjustVolume(0,"Dec");
						}
					}
				}
		);
		
		addSongBt.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(currSongE == null){
							MessageDialog.Error(playlistShell, "Error", "No song to play");
						}else{
							if(!mUser.addPE(currSongE)){
								MessageDialog.Error(playlistShell, "Error", "Song is already in playlist");
							}else{
								if(mUser.getPlaylist().size() == 1){
									nextSongE = currSongE;
									nextSongInfo.setText(nextSongE.sDescription());
								}
							}
						}
					}
				}
		);
		
		randSongBt.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						if(!dummyBt.getSelection()){
							dummyBt.setSelection(true);
							randSongBt.setText("Random mode on");
							MessageDialog.Notice(playlistShell, "Notice", "Please use the like/dislike feature (see \"Song features\")");
						}else{
							dummyBt.setSelection(false);
							if(mUser.getPlaylist().size() == 0){
								nextSongInfo.setText("You have no songs in your playlist");
							}else{
								nextSongE = mUser.getPlaylist().get(0);
								nextSongInfo.setText(nextSongE.sDescription());
							}
							randSongBt.setText("Random mode off");
						}
					}
				}
		);
		
		nextSongBt.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						browser.setUrl("http://www.blanksite.com/");
						if(dummyBt.getSelection()){
							addSongBt.setEnabled(true);
							if(!firstBt.getSelection()){
								firstBt.setSelection(true);
								nextSongE = Recomendation.getRecomendedSong();
							}
							currSongE = nextSongE;
							nextSongE = Recomendation.getRecomendedSong();
							currSongInfo.setText(currSongE.sDescription());
							nextSongInfo.setText(nextSongE.sDescription());
							String sUrl = "http://www.outofscopes.com/getSong.php?artist="+putMinus(currSongE.getArtist().getName())+"&track="+putMinusS(currSongE.getSong().getName());
							if(checkUrl(sUrl)){
								browser.setUrl("http://www.blanksite.com/");
								MessageDialog.Error(playlistShell, "Error", "Audio for this song was not found");
							}else{
								browser.setUrl(sUrl);
							}
						}else{
							addSongBt.setEnabled(false);
							if(mUser.getPlaylist().size() != 0){
								currIndex++;
								currSongE = nextSongE;
								if(currIndex >= mUser.getPlaylist().size()){
									currIndex = 0;
								}
								nextSongE = mUser.getNonRandPe(currIndex);
								currSongInfo.setText(currSongE.sDescription());
								nextSongInfo.setText(nextSongE.sDescription());	
								String sUrl = "http://www.outofscopes.com/getSong.php?artist="+putMinus(currSongE.getArtist().getName())+"&track="+putMinusS(currSongE.getSong().getName());
								if(checkUrl(sUrl)){
									browser.setUrl("http://www.blanksite.com/");
									MessageDialog.Error(playlistShell, "Error", "Audio for this song was not found");
								}else{
									browser.setUrl(sUrl);
								}
							}else{
								currSongInfo.setText("No song to play");
							}
						}
					}
				}
		);
		
		gotoSearchBt.addSelectionListener(
				new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						main.setPlaylistActive();
						if(!main.isSearchActive()){
							browser.setUrl("http://www.blanksite.com/");
							main.setSearchActive();
							Search search = new Search(passShellForward, mUser, main);
						}else{	
							main.findShell("searchShell").setFocus();
						}
					}
				}
		);
		
		Listener listener = new Listener () {
			public void handleEvent (Event e) {
				switch (e.type) {
				case SWT.Close:
					browser.setUrl("http://www.blanksite.com/");
					main.removeShell(playlistShell);
					main.setPlaylistNotActive();
					playlistShell.dispose();
					break;
				default:
		        }	
		   }
		};
		playlistShell.addListener (SWT.Close, listener);
		
		closeBt.addSelectionListener(
				new SelectionAdapter() {					
					public void widgetSelected(SelectionEvent e) {
						browser.setUrl("http://www.blanksite.com/");
						main.removeShell(playlistShell);
						main.setPlaylistNotActive();
						playlistShell.dispose();
					}
				}
		);
		
		playlistShell.pack();
		playlistShell.open();

		while (!playlistShell.isDisposed()) {
			if (!playlistDisplay.readAndDispatch())
				playlistDisplay.sleep();
		}
	}
	
	 public static String getLyrics(String track, String artist, Shell playlistShell)
     {
         String url = "http://www.lyrics.com/"+track+"-lyrics-"+artist+".html";
         String cutTxt = null;
         try {
             URL web = new URL(url);
             URLConnection yc = web.openConnection();
             BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
             String inputLine = null;
             StringBuffer txt = new StringBuffer();
             int j=-1,k=-1;
             while ((inputLine = in.readLine()) != null) {
                     inputLine = inputLine + "\n";
                     txt.append(inputLine);
                     if(txt.indexOf("<!-- CURRENT LYRIC --> ")!=-1){
                         j = txt.indexOf("<!-- CURRENT LYRIC --> ");
                     }
                     if(txt.indexOf("Lyrics powered by")!=-1){
                         k = txt.indexOf("Lyrics powered by");
                     }

             }

             in.close();
             cutTxt = txt.substring(j,k);
         } catch (Exception e) {
             MessageDialog.Error(playlistShell, "Error", "Lyrics were not found");
             return null;
         }            
         cutTxt = cutTxt.replace("&#xD;<br />", "");
         cutTxt = cutTxt.replace("<br />", "");    
         cutTxt = cutTxt.substring(173);
         return cutTxt;
     }
	
	  public static boolean checkUrl(String url)
      {
          try {
              URL web = new URL(url);
              URLConnection yc = web.openConnection();
              BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
              String inputLine = in.readLine();
              if (inputLine.equals("-Empty-"))
                  return true;                    
              in.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
          return false;
      }
}
